<?php

class Admin_ArticleController extends Zend_Controller_Action
{

    private $idcat = null;

    private $_model = null;

    public function init()
    {
        /* Initialize action controller here */
        $this->idcat = intval($this->_request->getParam("idcat"));
        $this->_model = new Application_Model_DbTable_Article();
    }

    public function indexAction()
    {
        // action body
        $this->view->headScript()->appendFile(
            $this->view->baseUrl("templates/admin/js/jquery.popupWindow.js")
        );
        // action body
        $choice = $this->_request->getParam("choice");
        if(!empty($choice)){
            $idarticle = intval($this->_request->getParam("id"));
            $rowArt = $this->_model->find($idarticle)->current();
            $n_status = ($rowArt->article_status)?0:1;
            if($choice=="once"){
                $this->_model->update(array("article_status"=>0),"categories_id=$rowArt->categories_id");
                $result = $this->_model->update(array("article_status"=>$n_status),"idarticles=$idarticle");
                $this->_helper->json->sendJson($result);
            }else if($choice=="multi"){
                $result = $this->_model->update(array("article_status"=>$n_status),"idarticles=$idarticle");
                $this->_helper->json->sendJson($result);
            }
        }
        
        $do = $this->_request->getParam("do");
        if(!empty($do)){
            $idarticle = intval($this->_request->getParam("id"));
            if($do=="local"){
                $value = intval($this->_request->getParam("value"));
                $result = $this->_model->update(array("article_local"=>$value),"idarticles=$idarticle");
                $this->_helper->json->sendJson($result);
            }
        }
        
        
        $idcat = intval($this->_request->getParam("idcat"));
        $mdCat = new Application_Model_DbTable_ArticleCategory();
        $rowCat = $mdCat->find($idcat)->current();        
        $this->view->cat = $rowCat;
    }

    public function addAction()
    {
        // action body
        if(!isset($this->idcat) || empty($this->idcat)){
            return $this->_redirect($this->view->url(array(
                'module' => "admin",
                'controller'=>"article",
                'action' => "list"
            ),null, true));
        }        
        
        $this->view->headScript()->appendFile(
            $this->view->baseUrl("ckeditor/ckeditor.js")
        );
        $mdCategory = new Application_Model_DbTable_ArticleCategory();
        $cat = $mdCategory->find($this->idcat)->current();
        
        $form = new Application_Form_Article();
        $form->createForm($cat->category_name,$cat->toArray());
        
        if($this->_request->isPost()){
            if($form->isValid($_POST)){
                $data = $form->getValues();
                $mdArticle = new Application_Model_DbTable_Article();
                $row = $mdArticle->createRow($data);
                $row->categories_id = $cat->idcategories;                
                // Người viết lấy từ session
                $row->users_id = 1;
                
                // Nếu bài viết có hình ảnh
                if($cat->has_image) {
                    if($form->article_image->isUploaded()){
                        $form->article_image->receive();
                        $filename = APPLICATION_PATH."/../public/images/article/".
                            basename($form->article_image->getFileName());
                        if(file_exists($filename)){
                            $image = new Cms_File_Image($filename);
                            $image->setDestinationPath(dirname($filename)."/thumb/");
                            $row->article_thumb = $image->CopyResize("{$cat->image_w}x{$cat->image_h}");
                            $row->article_image = $image->newname;
                        }
                    }
                }
                $row->article_alias = Cms_Filter_String::toAlias($row->article_name);
                $row->save();
                $this->_redirect($this->view->url(array(
                    'module'=>"admin",
                    'controller' => "article",
                    'action' => "index"
                )));
            }else{
                $errors = $form->getMessages();
                foreach($errors as $key=>$value){
                    $form->$key->setAttrib("class","error");
                }
            }
        }
        $this->view->catname = $cat->category_name;
        $this->view->form = $form;
        $this->view->image_h = $cat->image_h;
    }

    public function listAction()
    {
        // action body
        $idcat = intval($this->_request->getParam("idcat"));
        $mdCat = new Application_Model_DbTable_ArticleCategory();
        $rowCat = $mdCat->find($idcat)->current();
        
         //$articles = $rowCat->findDependentRowset("Application_Model_DbTable_Article");
         $sortby = $this->_request->getParam("sortby",null);
         $sorttype = $this->_request->getParam("sorttype", "asc");
         $filter_field = $this->_request->getParam("filter_field", null);
         $filter_value = $this->_request->getParam("filter_value");
         $this->view->sort = array("by"=>$sortby, "type"=>$sorttype);
         
         $filter['categories_id'] = $idcat;
         
         if(!empty($filter_field))
         {
            $filter[$filter_field] = $filter_value;
         }
         
         $adapter = $this->_model->fetchPaginatorAdapter($filter,$sortby,$sorttype);
         $paginator = new Zend_Paginator($adapter);
         
         //Show 10 dòng trên 1 trang
         $paginator->setItemCountPerPage(10);
         $page = $this->_request->getParam("page",1);
         $paginator->setCurrentPageNumber($page);
         $this->view->datas = $paginator;
         $this->view->cat = $rowCat;
         $this->_helper->layout()->disableLayout();
         $this->getResponse()->clearBody();
    }

    public function imagesAction()
    {
        // action body
        $this->_helper->layout()->disableLayout();
        $this->_response->clearBody();
    }

    public function editAction()
    {
        // action body
        // action body
        if(!isset($this->idcat) || empty($this->idcat)){
            return $this->_redirect($this->view->url(array(
                'module' => "admin",
                'controller'=>"article",
                'action' => "index"
            ),null, true));
        }        
        
        $this->view->headScript()->appendFile(
            $this->view->baseUrl("ckeditor/ckeditor.js")
        );
        $mdCategory = new Application_Model_DbTable_ArticleCategory();
        $cat = $mdCategory->find($this->idcat)->current();
        $form = new Application_Form_Article();
        $form->createForm($cat->category_name,$cat->toArray());
        $idart = $this->_request->getParam("idart");
        $article = $this->_model->find($idart)->current();
        $article->article_name = stripcslashes($article->article_name);        
        $article->article_content = stripcslashes($article->article_content);
        $article->article_description = stripcslashes($article->article_description);
        
        $form->populate($article->toArray());
        $this->view->thumb = $article->article_thumb;
        $this->view->image_h = $cat->image_h;
        
        if($this->_request->isPost()){
            if($form->isValid($_POST)){
                $data = $form->getValues();
                $row = $this->_model->createRow($data);
                $row->categories_id = $cat->idcategories;
                $row->article_image = $article->article_image;
                $row->article_thumb = $article->article_thumb;
                                  
                // Ngươời viết lấy từ session
                $row->users_id = 1;
                
                // 
                // Nếu bài viết có hình ảnh
                if($cat->has_image) {
                    if($form->article_image->isUploaded())
                    {
                        $form->article_image->receive();
                        $dir = $form->article_image->getDestination()."/";
                        $image_name = basename($form->article_image->getFileName());
                        $filename = $dir.$image_name;
                        
                        // Xoa hinh cu
                        if(is_file($dir.$article->article_image)) 
                            unlink($dir.$article->article_image);
                            
                        // Xoa thumb cu
                        if(is_file($dir."thumb/".$article->article_thumb)) 
                            unlink($dir."thumb/".$article->article_thumb);
                        
                        if(is_file($filename)){
                            $image = new Cms_File_Image($filename);
                            $image->setDestinationPath($dir."/thumb/");
                            $row->article_thumb = $image->CopyResize("{$cat->image_w}x{$cat->image_h}");
                            $row->article_image = $image->newname;
                        }
                    }
                }
                $row->article_alias = Cms_Filter_String::toAlias($row->article_name);
                $row->article_local = $article['article_local'];
                $datas = $row->toArray();
                unset($datas['idarticles']);
                $this->_model->update($datas, "idarticles='$row->idarticles'");
                
                $this->_redirect($this->view->url(array(
                    'module'=>"admin",
                    'controller' => "article",
                    'action' => "index",
                    'idcat'=>$this->idcat
                ),null, true));
            }else{
                $errors = $form->getMessages();
                foreach($errors as $key=>$value){
                    $form->$key->setAttrib("class","error");
                }
            }
        }
        $this->view->catname = $cat->category_name;
        $this->view->form = $form;        
    }
    
    public function delAction()
    {
        $idarticle = $this->_request->getParam("id", null);
        $result = null;
        if($idarticle!=null)
        {
            $row = $this->_model->find($idarticle)->current();
            $imagePath = APPLICATION_PATH."/../public/images/article/";
            if(is_file($imagePath."$row->article_image")){
                unlink($imagePath.$row->article_image);
            }
            $thumbPath = $imagePath."thumb/";
            if(is_file($thumbPath.$row->article_thumb)) {
                unlink($thumbPath.$row->article_thumb);
            }
            $result = $row->delete();
        }
        $this->_helper->json->sendJson($result);
    }

}













